<template>
  <div class="dict-detail">
    <!-- 上半部分：字典详细信息 -->
    <h2 class="title">字典详细信息</h2>
    <el-descriptions
        :column="2"
        border
        class="dict-info"
        label-class-name="description-label"
        content-class-name="description-content"
    >
      <el-descriptions-item label="字典名称">{{ dictDetails.dictName }}</el-descriptions-item>
      <el-descriptions-item label="字典中文名称">{{ dictDetails.dictNameCn }}</el-descriptions-item>
      <el-descriptions-item label="所属模块">{{ dictDetails.module }}</el-descriptions-item>
      <el-descriptions-item label="字典创建人">{{ dictDetails.createBy || '无' }}</el-descriptions-item>
      <el-descriptions-item label="字典创建时间">{{ formatDate(dictDetails.createTime) }}</el-descriptions-item>
      <el-descriptions-item label="字典最后修改时间">{{ formatDate(dictDetails.updateTime) }}</el-descriptions-item>
      <el-descriptions-item label="字典描述" :span="2">{{ dictDetails.dictDescription }}</el-descriptions-item>
      <el-descriptions-item label="相关枚举" :span="2">{{ dictDetails.enumClass }}</el-descriptions-item>
    </el-descriptions>

    <!-- 下半部分：字典值表格 -->
    <div class="dict-values">
      <div class="table-header">
        <h3>字典值信息</h3>
        <div class="button-group">
          <el-button type="primary" @click="toggleEdit" v-if="!isEditing">修改</el-button>
          <el-button type="success" @click="saveAllEdits" v-if="isEditing">保存</el-button>
          <el-button @click="cancelAllEdits" v-if="isEditing">取消</el-button>
          <el-button @click="addNewRow" v-if="isEditing" type="info">新增</el-button>
        </div>
      </div>

      <el-table :data="dictValues" border style="width: 100%;">
        <el-table-column prop="indexValue" label="索引值" width="100">
          <template #default="scope">
            <span>{{ scope.row.indexValue }}</span> <!-- 只读显示 -->
          </template>
        </el-table-column>

        <el-table-column prop="dictValue" label="字典值名称">
          <template #default="scope">
            <el-input v-if="isEditing" v-model="scope.row.dictValue" size="mini"></el-input>
            <span v-else>{{ scope.row.dictValue }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="dictValueCn" label="字典值中文名称">
          <template #default="scope">
            <el-input v-if="isEditing" v-model="scope.row.dictValueCn" size="mini"></el-input>
            <span v-else>{{ scope.row.dictValueCn }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="字典值备注">
          <template #default="scope">
            <el-input v-if="isEditing" v-model="scope.row.remark" size="mini"></el-input>
            <span v-else>{{ scope.row.remark }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" v-if="isEditing">
          <template #default="scope">
            <el-button type="danger" size="mini" @click="deleteRow(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { getDictDetails, getDictValues, batchDictValuesSave } from '@/service/admin/admin.service'; // 引入保存方法

export default {
  setup() {
    const route = useRoute();
    const dictId = route.params.id;
    const dictDetails = ref({});
    const dictValues = ref([]);
    const isEditing = ref(false); // 是否处于编辑状态
    const originalValues = ref([]); // 存储原始值，用于取消编辑

    // 格式化日期的方法
    const formatDate = (dateString) => {
      if (!dateString) return '无';
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}年${month}月${day}日${hours}时${minutes}分`;
    };

    // 获取字典详细信息
    const fetchDictDetails = () => {
      getDictDetails(dictId, (response) => {
        if (response.status === 'success') {
          dictDetails.value = response.data;
        }
      }, (error) => {
        console.error("获取字典详细信息失败：", error);
      });
    };

    // 获取字典值信息（保持接口提供的 indexValue，不做任何处理）
    const fetchDictValues = () => {
      getDictValues(dictId, (response) => {
        if (response.status === 'success') {
          dictValues.value = response.data;
          originalValues.value = JSON.parse(JSON.stringify(dictValues.value)); // 备份原始值
        }
      }, (error) => {
        console.error("获取字典值信息失败：", error);
      });
    };

    // 切换编辑状态
    const toggleEdit = () => {
      isEditing.value = true;
    };

    // 保存所有修改
    const saveAllEdits = () => {
      const params = {
        dictId: dictId,
        dictValues: dictValues.value,
      };
      batchDictValuesSave(params, (response) => {
        if (response.status === 'success') {
          console.log('保存成功');
          isEditing.value = false;
          fetchDictValues(); // 保存成功后刷新数据
        }
      }, (error) => {
        console.error("保存失败：", error);
      });
    };

    // 取消所有修改
    const cancelAllEdits = () => {
      dictValues.value = JSON.parse(JSON.stringify(originalValues.value)); // 恢复原始值
      isEditing.value = false;
    };

    // 新增一行时从0开始生成自增的 indexValue 值
    const addNewRow = () => {
      const newIndex = dictValues.value.length;
      dictValues.value.push({
        id: null,
        indexValue: newIndex, // 新增的数据行 indexValue 从0开始
        dictValue: '',
        dictValueCn: '',
        remark: '',
        dictId: dictId,
      });
    };

    // 删除一行
    const deleteRow = (index) => {
      dictValues.value.splice(index, 1);
    };

    onMounted(() => {
      fetchDictDetails();
      fetchDictValues();
    });

    return {
      dictDetails,
      dictValues,
      isEditing,
      toggleEdit,
      saveAllEdits,
      cancelAllEdits,
      addNewRow,
      deleteRow,
      formatDate,
    };
  },
};
</script>

<style scoped>
.dict-detail {
  padding: 20px;
}

.title {
  margin-bottom: 20px;
  font-size: 20px;
  font-weight: bold;
}

.dict-info {
  margin-bottom: 20px;
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 8px;
}

.description-label {
  font-weight: bold;
  color: #606266;
}

.description-content {
  color: #303133;
}

.dict-values {
  margin-top: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between; /* 将标题和按钮分开，一个在左，一个在右 */
  align-items: center; /* 垂直居中 */
  margin-bottom: 10px; /* 为标题和表格添加一些间距 */
}

.button-group {
  display: flex;
  gap: 10px; /* 控制按钮之间的间距 */
}

h2,
h3 {
  margin-bottom: 10px;
}
</style>
